﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data.OleDb;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using U8SrvTrans;
using System.Configuration;
using System.Dynamic;
using U8;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class postGy : IHttpHandler
    {
        public static readonly string bz = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
            string bearerToken = authHeader.Substring("Bearer ".Length).Trim();
            PetaPoco.Database dbw = new PetaPoco.Database(bz);

            
            object jsonData = "";
            XZ_RZBfaModel RZB = new XZ_RZBfaModel();
            FileLogHelper.WriteTxtLog("调用开始", "11");
            dynamic jsonF = new ExpandoObject();  //动态MODEL 存DATE
            dynamic res = new ExpandoObject();  //动态MODEL 返回值
            res.msg = "";
            TokenModel model = dbw.FirstOrDefault<TokenModel>("select  * from  Token  where token=@token and  DATEDIFF(DAY,date, GETDATE())=0", new { token = bearerToken });
            if (model == null)
            {
                res.code = 401;
                res.msg = "密钥不合法或者已经过期";
                res.data = "XXXX";
                res.count = 0;
                jsonData = JsonConvert.SerializeObject(res);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonData);
            }
            else
            {
                try
                {

            


                    byte[] postData = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(postData, 0, postData.Length);
                    string postDataString = System.Text.Encoding.UTF8.GetString(postData);
                    FileLogHelper.WriteTxtLog("调用开始", postDataString);

                    RZB.JSON = postDataString;
                    RZB.类型 = "工艺";
                    RZB.日期 = DateTime.Now;

                    InventoryInfo_GY U8fa = JsonConvert.DeserializeObject<InventoryInfo_GY>(postDataString);

                    var hasDuplicates = U8fa.InventorySub_GY.GroupBy(m => m.WcCode)
                                   .Any(g => g.Count() > 1);

                    if(hasDuplicates)
                    {
                        res.msg = "工序有重复";
                        res.code = 999;
                        RZB.是否成功 = "失败";
                        return;
                    }


                    bool hasNull = U8fa.InventorySub_GY.Any(p => p.row == null); // 使用LINQ Any方法检查是否有null值
                    if (hasNull)
                    {
                        res.msg = "JSON空值";
                        res.code = 999;
                        RZB.是否成功 = "失败";
                        return;
                    }



                    U8fa.cmker = model.name;
                    InventoryInfo_GY mm = dbw.SingleOrDefault<InventoryInfo_GY>("SELECT Version,VersionDesc ,a.PRoutingId,VersionEffDate  from sfc_prouting a,sfc_proutingpart b where a.PRoutingId = b.PRoutingId  and  exists(select  1 from bas_part c where b.PartId = c.PartId and invcode = '" + U8fa.cInvCode + "') and  LEFT('" + U8fa.VersionEffDate + "',10) = CONVERT(varchar(100),VersionEffDate, 23) ");

                    //判断版本号、开始日期是否重复
                    if (mm==null)
                    {
                        InventoryInfo_GY  aaa = dbw.SingleOrDefault<InventoryInfo_GY>("SELECT   isnull(max(Version),0)+10  Version,CASE WHEN   max(DATEADD(day, 1, VersionEffDate))>CONVERT(VARCHAR, GETDATE(), 23)  THEN  max(DATEADD(day, 1, VersionEffDate)) ELSE  CONVERT(VARCHAR, GETDATE(), 23) END  VersionEffDate   from sfc_prouting a,sfc_proutingpart b where a.PRoutingId = b.PRoutingId  and  exists(select  1 from bas_part c where b.PartId = c.PartId and invcode = '" + U8fa.cInvCode + "')  ");
                        U8fa.VersionEffDate = U8fa.VersionEffDate;      //取接口的版本日期
                        U8fa.VersionDesc = "工艺版本:"+aaa.Version;      //查询该货品的版本号，有则加10 无则10
                        U8fa.Version = aaa.Version;
                    }
                    else
                    {
                        U8fa.PRoutingId = mm.PRoutingId;             //保留原来版本号
                        U8fa.VersionEffDate = mm.VersionEffDate;      //保留原来版本号
                        U8fa.VersionDesc = mm.VersionDesc;
                        U8fa.Version = mm.Version;
                    }





                    //判断存货数据是否正常
                    if (dbw.SingleOrDefault<int>("select  (1) from inventory  WHERE  cinvcode='" + U8fa.cInvCode + "'  and  bSelf =1") == 0)
                    {
                        res.msg = "物料非自制属性";
                       
                    }


                    for (int i = 0; i < U8fa.InventorySub_GY.Count; i++)
                    {
                        dynamic  ss = dbw.SingleOrDefault<dynamic>("SELECT OperationId,Description  from sfc_operation  where OpCode='" + U8fa.InventorySub_GY[i].OpCode + "'");
                        //判断工序代号
                        if (ss == null)
                        {
                            U8fa.InventorySub_GY[i].Description = ss.Description;
                            U8fa.InventorySub_GY[i].WcId = ss.WcId;
                            res.msg = U8fa.InventorySub_GY[i].OpCode + "工序代号不存在";
                        }
                        else
                        {
                            long a1a = ss.OperationId;
                            U8fa.InventorySub_GY[i].OperationId = a1a.ToString();
                            U8fa.InventorySub_GY[i].Description = ss.Description;
                        }

                        string sss = dbw.SingleOrDefault<string>("SELECT WcId from sfc_workcenter  where WcCode='" + U8fa.InventorySub_GY[i].WcCode + "'");
                        //判断工作中心编码
                        if (dbw.SingleOrDefault<int>("SELECT WcId  from sfc_workcenter  where WcCode='" + U8fa.InventorySub_GY[i].WcCode + "'") == 0)
                        {
                            res.msg = U8fa.InventorySub_GY[i].WcCode + "工作中心编码不存在";
                        }
                        else
                        {
   
                            U8fa.InventorySub_GY[i].WcId = sss;
                        }
                    }


                    if(res.msg!="")
                    {
                        res.code = 999;
                        RZB.是否成功 = "失败";
                        return;
                    }
                    Inventory_gy aa = new Inventory_gy();

                    res.msg = aa.Save(U8fa);
                    if (res.msg != "")
                    {
                        res.code = 999;
                        RZB.是否成功 = "失败";
                        return;
                    }


                    RZB.是否成功 = "成功";
                    res.code = 200;
                    res.msg = "CO成功";

                }

                catch (Exception ee)
                {
                    if (ee.Message.Length > 50)
                    {
                        res.msg = ee.Message.Substring(0, 50);
                    }
                    else
                    {
                        res.msg = ee.Message;
                    }
                    res.code = 999;

                }
                finally
                {
                    dbw.Save(RZB);
                    jsonData = JsonConvert.SerializeObject(res);
                    context.Response.ContentType = "application/json";
                    context.Response.Write(jsonData);


                }
            }
            


        
        }




        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string res(string ccode, string msg, string jsonData)
        {
            string resstr = "";


            return resstr;
        }


    }
}